package com.link.gateway.core.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.link.gateway.core.cllog.LCLogger;
import com.link.gateway.core.utils.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.annotation.Resource;
import java.sql.SQLException;

@Configuration
public class DataSourceConfig {
    @Resource
    private Environment env;

    @Bean
    public DruidDataSource masterDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(env.getProperty("spring.datasource.driverClassName"));
        druidDataSource.setUsername(env.getProperty("spring.datasource.username"));
        druidDataSource.setPassword(env.getProperty("spring.datasource.password"));
        druidDataSource.setMaxActive(Integer.valueOf(env.getProperty("spring.datasource.max-active")));
        druidDataSource.setInitialSize(Integer.valueOf(env.getProperty("spring.datasource.initial-size")));
        druidDataSource.setMinIdle(Integer.valueOf(env.getProperty("spring.datasource.min-idle")));
        String minEITM = env.getProperty("spring.datasource.minEvictableIdleTimeMillis");
        if (StringUtils.isNotBlank(minEITM)) {
            druidDataSource.setMinEvictableIdleTimeMillis(Integer.valueOf(minEITM));
        }

        String maxEITM = env.getProperty("spring.datasource.maxEvictableIdleTimeMillis");
        if (StringUtils.isNotBlank(maxEITM)) {
            druidDataSource.setMaxEvictableIdleTimeMillis(Integer.valueOf(maxEITM));
        }

        String tberm = env.getProperty("spring.datasource.timeBetweenEvictionRunsMillis");
        if (StringUtils.isNotBlank(tberm)) {
            druidDataSource.setMinEvictableIdleTimeMillis(Integer.valueOf(tberm));
        }

        String maxIdle = env.getProperty("spring.datasource.max-idle");
        if (StringUtils.isNotBlank(maxIdle)) {
            druidDataSource.setMaxIdle(Integer.valueOf(maxIdle));
        }
        druidDataSource.setTestOnBorrow(true);
        druidDataSource.setTestWhileIdle(true);
        druidDataSource.setValidationQuery("select 1 from dual");
        druidDataSource.setUrl(env.getProperty("spring.datasource.url"));
        try {
            druidDataSource.setFilters("stat");
        } catch (SQLException e) {
            LCLogger.withException(e.getMessage());
        }
        return druidDataSource;

    }

}
